<template>
  <div class="chat-container">
    <div class="chat-messages" ref="chatMessagesRef">
      <div v-for="(message, index) in messages" :key="index" >
        <small :class="['nick-name', `${message.senderRole.toLowerCase()}-nick-name`]">{{ message.senderNickName }}</small>
        <div :class="['message', `${message.senderRole.toLowerCase()}-message`]">
         
        {{ message.content }}
        <small class="message-time">{{ formatTime(message.timestamp) }}</small>
        </div>
        
      </div>
    </div>
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        placeholder="输入消息..."
        @keyup.enter="sendMessage"
      >
        <template #append>
          <el-button @click="sendMessage">发送</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useUserStore } from '@/stores/user'
import { fetchChatHistory, sendMessage as apiSendMessage } from '@/api/customerService'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const messages = ref([])
const inputMessage = ref('')
const ws = ref(null)
const chatMessagesRef = ref(null)
const conversationId = ref(null)

const connectWebSocket = () => {
  const userId = userStore.userInfo?.userId;
  if (!userId) {
    console.error('No userId available for WebSocket connection');
    ElMessage.error('无法建立WebSocket连接：用户ID不可用');
    return;
  }

  ws.value = new WebSocket(`ws://jevon-blog-api.com:3000/ws?userId=${userId}&isAdmin=false`);
  
  ws.value.onopen = () => {
    console.log('WebSocket连接已建立');
  };

  ws.value.onmessage = (event) => {
    console.log('收到消息:', event.data);
    const message = JSON.parse(event.data);
    if (message.conversationId === conversationId.value) {
      messages.value.push(message);
      scrollToBottom();
    }
  };

  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭');
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error);
    ElMessage.error('WebSocket连接错误');
  };
};

const loadChatHistory = async () => {
  const userId = userStore.userInfo?.userId;
  if (!userId) {
    console.error('No userId available for loading chat history');
    ElMessage.error('无法加载聊天历史：用户ID不可用');
    return;
  }

  try {
    const response = await fetchChatHistory();
    if (response.code === 0 && Array.isArray(response.data)) {
      messages.value = response.data;
      if (response.data.length > 0) {
        conversationId.value = response.data[0].conversationId;
      } else {
        // 如果没有历史消息，创建新的会话ID
        conversationId.value = `conv_${userId}_admin`;
      }
    } else {
      messages.value = [];
      console.error('Invalid chat history data:', response);
    }
    scrollToBottom();
  } catch (error) {
    console.error('加载聊天历史失败:', error);
    ElMessage.error('加载聊天历史失败');
    messages.value = [];
  }
};

const sendMessage = async () => {
  const userId = userStore.userInfo?.userId;
  if (!inputMessage.value.trim() || !userId) {
    ElMessage.warning('请输入消息内容');
    return;
  }

  try {
    const response = await apiSendMessage(
      conversationId.value,
      inputMessage.value,
    );
    if (response.code !== 0) {
      throw new Error(response.message || '发送消息失败');
    }

    const newMessage = {
      id: response.data.messageId,
      conversationId: response.data.conversationId,
      senderId: userId,
      receiverId: response.data.receiver, // 这里要确保返回的 receiver 是具体的ID
      content: inputMessage.value,
      timestamp: new Date().toISOString(),
      senderRole: 'USER',
      receiverRole: 'ADMIN',
    };

    messages.value.push(newMessage);
    inputMessage.value = '';
    scrollToBottom();
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error(error.message || '发送消息失败');
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
    }
  });
};

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

onMounted(() => {
  loadChatHistory();
  connectWebSocket();
});

onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 88vh;
}

.chat-messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
}

.message {
  margin-bottom: 10px;
  padding: 5px 10px;
  border-radius: 5px;
  max-width: 70%;
  position: relative;
}

.user-message {
  align-self: flex-end;
  background-color: #e6f7ff;
  margin-left: auto;
}

.admin-message {
  align-self: flex-start;
  background-color: #f0f0f0;
  margin-right: auto;
}
.nick-name{
  font-size: 1.5em;
  color: #888;
  display: block;
  text-align: left;
  margin-top: -2px;
}
.user-nick-name {
  align-self: flex-end;
  margin-left: auto;
  color:red
}

.admin-nick-name {
  align-self: flex-start;
  margin-right: auto;
}

.message-time {
  font-size: 0.8em;
  color: #888;
  display: block;
  text-align: right;
  margin-top: 2px;
}

.chat-input {
  padding: 10px;
}
</style>